from music21 import stream, note, duration, midi, tempo, meter
from symbol_map import SYMBOL_TO_NOTE

def parse_symbols_to_stream(symbols):
    s = stream.Stream()
    s.append(tempo.MetronomeMark(number=120))
    s.append(meter.TimeSignature('4/4'))
    # 简单按x坐标排序，模拟从左到右播放
    symbols = sorted(symbols, key=lambda x: x['bbox'][0])
    for sym in symbols:
        info = SYMBOL_TO_NOTE.get(sym['class'])
        if not info:
            continue
        if info['type'] == 'note':
            n = note.Note('C4')  # 这里只做示例，实际应根据y坐标推断音高
            n.duration = duration.Duration(info['duration'])
            s.append(n)
        elif info['type'] == 'rest':
            r = note.Rest()
            r.duration = duration.Duration(info['duration'])
            s.append(r)
    return s

def stream_to_midi_file(s, midi_path):
    mf = midi.translate.streamToMidiFile(s)
    mf.open(midi_path, 'wb')
    mf.write()
    mf.close() 